package com.pinc.poop;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public abstract class PincCalendarView extends LinearLayout {
	protected Context mContext;
	protected PincCalendarGridView[][] mGridView;
	protected PincDate mDate;
	private PincDate mToday;

	public PincCalendarView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		LayoutInflater.from(context).inflate(getLayoutResource(), this, true);
		Resources res = getResources();

		mGridView= new PincCalendarGridView[6][7];
		String pkgname = context.getPackageName();
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 7; j++) {
				int resID = res.getIdentifier(String.format("%s%d_%d", getGridIdName(), j+1, i+1), "id", pkgname);
				mGridView[i][j] = (PincCalendarGridView) findViewById(resID);
			}
		}

		mToday = new PincDate();
		mToday.setToNow();
		mDate = new PincDate(mToday);
	}

	protected abstract int getLayoutResource();
	protected abstract String getGridIdName();
	protected abstract View.OnClickListener getClickListener(PincDate date);
	public abstract void prepareData();
	public abstract void updateData();
	public abstract void clearData();

	public void setDate(PincDate date)
	{
		mToday.setToNow();
		mDate.setDate(date);
	}

	public void nextMonth(int n)
	{
		mToday.setToNow();
		mDate.nextMonth(n);
	}

	public void prepareBaseView()
	{
		PincDate localDate = new PincDate(mDate);
		localDate.go2FirstDayofMonth().go2FirstDayofWeek();

		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 7; j++) {
				mGridView[i][j].isCurMonth = (mDate.month == localDate.month);
				mGridView[i][j].isToday = localDate.SameDay(mToday);
				mGridView[i][j].monthDay = localDate.monthDay;
				if ( localDate.before(mToday) && (localDate.month == mDate.month) || localDate.SameDay(mToday))
				{
					mGridView[i][j].listener = getClickListener(localDate);
				}
				else
					mGridView[i][j].listener = null;
				localDate.nextDay(1);
			}
		}
	}

	public void updateBaseView()
	{
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 7; j++) {
				mGridView[i][j].updateBaseView();
			}
		}
	}

}
